package com.nlp.visualization.controller.spring.config;

import com.nlp.visualization.pojo.db.TApiStatistics;
import com.nlp.visualization.service.backEnd.IApiCountService;
import com.nlp.visualization.utils.TimeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author LXM
 * @Title: NLPVisualizationTools
 * @Description:
 * @date 2018/5/16下午3:04
 */
public class APIHandlerIntercepter implements HandlerInterceptor {


    private Logger logger = LoggerFactory.getLogger(APIHandlerIntercepter.class);

    private static final String SEG = "词法分析接口";

    private static final String SEN = "句法分析接口";

    private static final String DISCOURSE = "语篇分析接口";

    private static final String WEIBO = "微博分析接口";

    @Autowired
    private IApiCountService apiService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.indexOf("api") > 0) {

            TApiStatistics tApiStatistics = new TApiStatistics();

            if (requestURI.indexOf("segment") > 0) {
                tApiStatistics.setName(SEG);

            } else if (requestURI.indexOf("sentence") > 0) {
                tApiStatistics.setName(SEN);


            } else if (requestURI.indexOf("discourse") > 0) {
                tApiStatistics.setName(DISCOURSE);

            } else if (requestURI.indexOf("weibo") > 0) {
                tApiStatistics.setName(WEIBO);

            } else {
                tApiStatistics.setName("nbame");
            }
            tApiStatistics.setUri(requestURI);
            tApiStatistics.setIp(request.getLocalAddr());
            tApiStatistics.setTime(TimeHelper.getTime().longValue());
            apiService.save(tApiStatistics);
            logger.info(request.getLocalAddr() + "访问了:" + tApiStatistics.getName());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
